﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using static BW.Mes.WinForms.BasicData.BomForm;
using BW.Mes.WinForms.BasicData; // 确保BomSparepartModel和ProductForm.ProductModel可用
using Microsoft.VisualBasic;

namespace BW.Mes.WinForms.BasicData
{
    public partial class AddBomForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient = new HttpClient();
        private readonly string _apiBaseUrl = "http://120.26.197.100:8022";
        private BindingList<BomSparepartViewModel> spareparts = new BindingList<BomSparepartViewModel>();

        public AddBomForm()
        {
            InitializeComponent();
            comboBoxEditType.Properties.Items.Clear();
            comboBoxEditType.Properties.Items.AddRange(new string[] { "成品", "半成品", "原材料", "其他" });
            comboBoxEditType.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            comboBoxEditType.Properties.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.Flat;
            comboBoxEditType.Properties.Appearance.BorderColor = System.Drawing.Color.LightGray;
            comboBoxEditType.Properties.Appearance.Options.UseBorderColor = true;
            comboBoxEditType.Properties.Appearance.BackColor = System.Drawing.Color.White;
            comboBoxEditType.Properties.Appearance.Options.UseBackColor = true;
            comboBoxEditType.Properties.NullText = "请选择类型";
            // 不再自动加载所有配件
            // this.Load += AddBomForm_Load;
            // 只绑定一次数据源
            gridControl1.DataSource = spareparts;
            SetupSparepartsGridDev();
            this.Load += async (s, e) => { await AutoGenBomCode(); };
        }

        private async Task AutoGenBomCode()
        {
            string today = DateTime.Now.ToString("yyyyMMdd");
            string prefix = $"Bom{today}";
            int maxSerial = 0;
            try
            {
                _httpClient.DefaultRequestHeaders.Accept.Clear();
                _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                var response = await _httpClient.GetAsync($"{_apiBaseUrl}/T2/Bom/GetBom");
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    var jsonObject = JObject.Parse(json);
                    var listToken = jsonObject["pageDatas"] ?? jsonObject["data"] ?? jsonObject["result"];
                    if (listToken != null)
                    {
                        var boms = JsonConvert.DeserializeObject<List<BomModel>>(listToken.ToString());
                        if (boms != null)
                        {
                            foreach (var item in boms)
                            {
                                string code = item.BomCode;
                                if (!string.IsNullOrEmpty(code) && code.StartsWith(prefix))
                                {
                                    string serialStr = code.Substring(prefix.Length);
                                    if (int.TryParse(serialStr, out int serial))
                                    {
                                        if (serial > maxSerial) maxSerial = serial;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch { }
            string newCode = $"{prefix}{(maxSerial + 1).ToString("D3")}";
            textEditCode.Text = newCode;
            textEditCode.Properties.ReadOnly = true;
        }

        private async void btnOK_Click(object sender, EventArgs e)
        {
            gridView1.PostEditor();
            gridView1.UpdateCurrentRow();
            // 调试：弹窗显示spareparts内容
            var debug = string.Join("\n", spareparts.Select(x => $"{x.ProductCode} 数量={x.NNumber} 损耗率={x.BomBfb}"));
            MessageBox.Show(debug, "spareparts调试");
            var model = new
            {
                BomCode = textEditCode.Text,
                BomName = textEditName.Text,
                Version = textEditVersion.Text,
                BomType = comboBoxEditType.Text,
                BomNumber = textEditNumber.Text,
                BomMoney = textEditMoney.Text,
                BomMsg = textEditMsg.Text,
                CreatedBy = "yourUser"
            };
            try
            {
                // 保存前再次校验编码唯一性
                _httpClient.DefaultRequestHeaders.Accept.Clear();
                _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                var checkResponse = await _httpClient.GetAsync($"{_apiBaseUrl}/T2/Bom/GetBom");
                if (checkResponse.IsSuccessStatusCode)
                {
                    var checkJson = await checkResponse.Content.ReadAsStringAsync();
                    var checkObj = JObject.Parse(checkJson);
                    var checkListToken = checkObj["pageDatas"] ?? checkObj["data"] ?? checkObj["result"];
                    if (checkListToken != null)
                    {
                        var boms = JsonConvert.DeserializeObject<List<BomModel>>(checkListToken.ToString());
                        if (boms.Any(b => b.BomCode == textEditCode.Text))
                        {
                            XtraMessageBox.Show($"BOM编码 {textEditCode.Text} 已存在，请刷新后重试！", "编码重复", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            await AutoGenBomCode();
                            return;
                        }
                    }
                }
                string jsonData = JsonConvert.SerializeObject(model);
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                _httpClient.DefaultRequestHeaders.Accept.Clear();
                _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                var response = await _httpClient.PostAsync($"{_apiBaseUrl}/T2/Bom/AddBom", content);
                response.EnsureSuccessStatusCode();
                // 获取BOM主表Id
                var responseBody = await response.Content.ReadAsStringAsync();
                var bomId = ExtractBomIdFromResponse(responseBody); // 你已实现
                // 循环提交配件
                foreach (var part in spareparts)
                {
                    part.CreatedBy = "yourUser";
                    part.CreatedAt = DateTime.Now;
                    // 如果后端需要BomId，取消注释下一行
                    // part.BomId = bomId;
                    var partToPost = new
                    {
                        Product_id = part.Id, // 关键：提交时用Product_id字段
                        Spend = part.Spend,
                        NNumber = part.NNumber,
                        BomBfb = part.BomBfb,
                        ParentId = part.ParentId, // 这里改为用实际的ParentId
                        CreatedBy = part.CreatedBy,
                        CreatedAt = part.CreatedAt,
                        UpdatedAt = part.UpdatedAt
                    };
                    string partJson = JsonConvert.SerializeObject(partToPost);
                    var partContent = new StringContent(partJson, Encoding.UTF8, "application/json");
                    await _httpClient.PostAsync($"{_apiBaseUrl}/T2/Bom/AddBomSparepart", partContent);
                }
                XtraMessageBox.Show("新增成功！");
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"新增失败: {ex.Message}");
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private async void AddBomForm_Load(object sender, EventArgs e)
        {
            // 移除AddBomForm_Load和LoadAllSpareparts的调用
        }

        private async Task LoadAllSpareparts()
        {
            var client = new System.Net.Http.HttpClient();
            var response = await client.GetAsync("http://120.26.197.100:8022/T2/Bom/GetBomSparepart");
            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();
                var obj = Newtonsoft.Json.Linq.JObject.Parse(json);
                var listToken = obj["pageDatas"] ?? obj["data"] ?? obj["result"];
                var allSpareparts = listToken != null
                    ? Newtonsoft.Json.JsonConvert.DeserializeObject<List<BomSparepartViewModel>>(listToken.ToString())
                    : new List<BomSparepartViewModel>();
                spareparts.Clear();
                foreach (var item in allSpareparts)
                {
                    spareparts.Add(item);
                }
                // 不再重新赋值DataSource和Columns.Clear()
                // gridControl1.DataSource = null;
                // gridView1.Columns.Clear();
                // gridControl1.DataSource = allSpareparts;
                SetupSparepartsGridDev();
            }
        }

        private long ExtractBomIdFromResponse(string responseBody)
        {
            var obj = Newtonsoft.Json.Linq.JObject.Parse(responseBody);
            return obj["id"] != null ? (long)obj["id"] : 0;
        }

        private void SetupSparepartsGridDev()
        {
            gridControl1.DataSource = spareparts;
            gridView1.Columns.Clear();
            // 配件ID列
            var colId = gridView1.Columns.AddField("Id");
            colId.Visible = true;
            colId.VisibleIndex = 0;
            colId.Caption = "配件ID";
            colId.OptionsColumn.AllowEdit = false;
            // 序号列
            var colIndex = gridView1.Columns.AddField("序号");
            colIndex.Visible = true;
            colIndex.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
            colIndex.VisibleIndex = 1;
            colIndex.OptionsColumn.AllowEdit = false;
            // 其它字段列
            gridView1.Columns.AddVisible("ProductCode", "物品编号").OptionsColumn.AllowEdit = false;
            gridView1.Columns.AddVisible("ProductName", "物品名称").OptionsColumn.AllowEdit = false;
            gridView1.Columns.AddVisible("Specification", "规格型号").OptionsColumn.AllowEdit = false;
            gridView1.Columns.AddVisible("Unit", "单位").OptionsColumn.AllowEdit = false;
            gridView1.Columns.AddVisible("Spend", "品牌").OptionsColumn.AllowEdit = false;
            gridView1.Columns.AddVisible("NNumber", "配件数量").OptionsColumn.AllowEdit = true;
            gridView1.Columns.AddVisible("BomBfb", "损耗率").OptionsColumn.AllowEdit = true;

            gridView1.OptionsBehavior.Editable = true;
            // 配件数量用SpinEdit
            var spinEdit = new DevExpress.XtraEditors.Repository.RepositoryItemSpinEdit();
            spinEdit.MinValue = 0;
            spinEdit.IsFloatValue = false;
            spinEdit.NullText = "";
            gridControl1.RepositoryItems.Add(spinEdit);
            gridView1.Columns["NNumber"].ColumnEdit = spinEdit;

            // 损耗率用TextEdit并显示百分号
            var percentEdit = new DevExpress.XtraEditors.Repository.RepositoryItemTextEdit();
            percentEdit.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
            percentEdit.Mask.EditMask = "P"; // 百分比格式
            percentEdit.Mask.UseMaskAsDisplayFormat = true;
            percentEdit.NullText = "";
            gridControl1.RepositoryItems.Add(percentEdit);
            gridView1.Columns["BomBfb"].ColumnEdit = percentEdit;

            // 序号列数据
            gridView1.CustomUnboundColumnData += (s, e) =>
            {
                if (e.Column.FieldName == "序号" && e.IsGetData)
                {
                    e.Value = e.ListSourceRowIndex + 1;
                }
            };
            // 暂无数据提示
            gridView1.CustomDrawEmptyForeground += (s, e) =>
            {
                var view = s as DevExpress.XtraGrid.Views.Grid.GridView;
                if (view.RowCount == 0)
                {
                    string text = "暂无数据";
                    var rect = e.Bounds;
                    var font = e.Appearance.Font;
                    var color = System.Drawing.Color.Gray;
                    e.Graphics.DrawString(text, font, new System.Drawing.SolidBrush(color), rect, new System.Drawing.StringFormat { Alignment = System.Drawing.StringAlignment.Center, LineAlignment = System.Drawing.StringAlignment.Center });
                }
            };
        }

        private void btnAddSparepart_Click(object sender, EventArgs e)
        {
            var allProducts = GetAllProducts();
            var selectForm = new ProductSelectForm(allProducts);
            if (selectForm.ShowDialog() == DialogResult.OK)
            {
                foreach (var product in selectForm.SelectedProducts)
                {
                    if (spareparts.Any(x => x.Id == product.Id)) continue;
                    // 弹窗输入父级ID
                    string input = Prompt.ShowDialog("请输入父级ID（如无父级请输入0）", "父级ID");
                    long parentId = 0;
                    long.TryParse(input, out parentId);
                    var newPart = new BomSparepartViewModel
                    {
                        Id = product.Id,
                        ProductCode = product.ProductCode,
                        ProductName = product.ProductName,
                        Specification = product.Specification,
                        Unit = product.Unit,
                        Spend = product.MaterialName,
                        NNumber = 0,
                        BomBfb = "0%",
                        ParentId = parentId
                    };
                    spareparts.Add(newPart);
                }
            }
        }

        private void btnRemoveSparepart_Click(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var part = gridView1.GetRow(gridView1.FocusedRowHandle) as BomSparepartViewModel;
                if (part != null)
                {
                    spareparts.Remove(part);
                }
            }
        }

        private void groupBoxSpareparts_Enter(object sender, EventArgs e)
        {

        }

        private void LoadBomData(BomModel model)
        {
            textEditMoney.Text = model.BomMoney.ToString();
        }

        private void AddBomForm_Load_1(object sender, EventArgs e)
        {

        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        // 示例：获取所有产品的方法（请根据实际情况实现）
        private List<ProductForm.ProductModel> GetAllProducts()
        {
            var client = new HttpClient();
            var response = client.GetAsync("http://120.26.197.100:8022/T2/Product/GetProduct?PageIndex=1&PageSize=1000").Result;
            if (response.IsSuccessStatusCode)
            {
                var json = response.Content.ReadAsStringAsync().Result;
                var obj = JObject.Parse(json);
                var listToken = obj["pageDatas"] ?? obj["data"] ?? obj["result"];
                return listToken != null
                    ? JsonConvert.DeserializeObject<List<ProductForm.ProductModel>>(listToken.ToString())
                    : new List<ProductForm.ProductModel>();
            }
            return new List<ProductForm.ProductModel>();
        }
    }
}

public static class Prompt
{
    public static string ShowDialog(string text, string caption)
    {
        Form prompt = new Form()
        {
            Width = 450,
            Height = 200,
            FormBorderStyle = FormBorderStyle.FixedDialog,
            Text = caption,
            StartPosition = FormStartPosition.CenterScreen
        };
        Label textLabel = new Label() { Left = 30, Top = 30, Text = text, Width = 360 };
        TextBox textBox = new TextBox() { Left = 30, Top = 65, Width = 360 };
        Button confirmation = new Button() { Text = "确定", Left = 310, Width = 80, Top = 110, DialogResult = DialogResult.OK };
        confirmation.Click += (sender, e) => { prompt.Close(); };
        prompt.Controls.Add(textBox);
        prompt.Controls.Add(confirmation);
        prompt.Controls.Add(textLabel);
        prompt.AcceptButton = confirmation;
        return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
    }
}